package com.ruoyi.mdm.service.impl;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mdm.domain.ChannelInfo;
import com.ruoyi.mdm.domain.SearchConditionInfo;
import com.ruoyi.mdm.mapper.ChannelInfoMapper;
import com.ruoyi.mdm.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class MdmApiServiceImpl implements IMdmApiService {

    @Value("${shiseido.appSecret}")
    public String appSecret;

    @Value("${shiseido.appid}")
    public String appId;

    @Autowired
    public RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private IMasterDataService masterDataService;

    @Autowired
    private ChannelInfoMapper channelInfoMapper;

    /**
     * 高级查询数据服务信息
     *
     * @param searchConditionInfo 检索条件
     * @return 数据服务信息
     */
    @Override
    public Object selectSkuInfoData(HttpServletRequest request, SearchConditionInfo searchConditionInfo) {

        TableDataInfo rspData = new TableDataInfo();

        // 服务渠道编码 必须
        if (StringUtils.isEmpty(searchConditionInfo.getChannelCode())) {
            rspData.setCode(100);
            rspData.setMsg("服务渠道编码参数必须!");
            return rspData;
        }

        ChannelInfo channelInfo = channelInfoMapper.selectChannelInfoByCode(searchConditionInfo.getChannelCode());
        if (channelInfo == null) {
            rspData.setCode(100);
            rspData.setMsg("服务渠道不存在!");
            return rspData;
        }

        // 检索维度 必须
        if (StringUtils.isEmpty(searchConditionInfo.getSearchDimension())) {
            rspData.setCode(100);
            rspData.setMsg("检索维度参数必须!");
            return rspData;
        }

        // BODY拼接 需要确认 Todo
        StringBuffer requestBody = new StringBuffer();
        if (StringUtils.isNotEmpty(searchConditionInfo.getChannelCode())) {
            requestBody = requestBody.append("channelCode=").append(searchConditionInfo.getChannelCode());
        }
        if (StringUtils.isNotEmpty(searchConditionInfo.getSearchDimension())) {
            requestBody = requestBody.append("searchDimension=").append(searchConditionInfo.getSearchDimension());
        }
        if (StringUtils.isNotEmpty(searchConditionInfo.getKeyword())) {
            requestBody = requestBody.append("keyword=").append(searchConditionInfo.getKeyword());
        }
        if (StringUtils.isNotEmpty(searchConditionInfo.getSalesChannelCode())) {
            requestBody = requestBody.append("salesChannelCode=").append(searchConditionInfo.getSalesChannelCode());
        }
        if (StringUtils.isNotEmpty(searchConditionInfo.getGoodsCode())) {
            requestBody = requestBody.append("goodsCode=").append(searchConditionInfo.getGoodsCode());
        }
        if (StringUtils.isNotEmpty(searchConditionInfo.getBarCode())) {
            requestBody = requestBody.append("barCode=").append(searchConditionInfo.getBarCode());
        }
        if (searchConditionInfo.getSalePrice() != null) {
            requestBody = requestBody.append("salePrice=").append(searchConditionInfo.getSalePrice());
        }

        // 签名验证
        rspData = checkSign(request, requestBody.toString());
        if (rspData.getCode() != 200) {
            return rspData;
        }

        // 检索条件
        return masterDataService.searchMasterData(searchConditionInfo);
    }

    /**
     * 签名认证
     *
     * @param request
     * @return
     */
    public TableDataInfo checkSign(HttpServletRequest request, String requestBody) {

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);

        // 假设过期时间阈值为10分钟
        long expireThreshold = 10 * 60 * 1000;
        String msg = "";
        String appid = request.getHeader("appid");
        log.info("--------------appid = " + appid);

        String nonce = request.getHeader("nonce");
        log.info("--------------nonce = " + nonce);

        if (StringUtils.isEmpty(nonce)) {

            rspData.setCode(100);
            rspData.setMsg("流水号参数不可为空!");

            return rspData;
        } else {

//            // 解决重复请求   由于检索分页请求  不做限制
//            String redisNonce= (String) redisTemplate.opsForValue().get("redisNonce");
//            if (StringUtils.equals(nonce, redisNonce)){
//
//                rspData.setCode(100);
//                rspData.setMsg("流水号有效期内重复!");
//
//                return rspData;
//            } else {
//                redisTemplate.opsForValue().set("redisNonce", nonce);
//                redisTemplate.expire("redisNonce", expireThreshold, TimeUnit.SECONDS);
//            }
        }

        // 请求有效期校验
//        String timestamp = request.getHeader("timestamp");
//        if (StringUtils.isEmpty(timestamp)) {
//            rspData.setCode(100);
//            rspData.setMsg("时间戳参数不可为空!");
//            return rspData;
//        } else {
//            long currentTimeStamp = System.currentTimeMillis();
//            long timeDiff = currentTimeStamp - Long.parseLong(timestamp);
//            if (timeDiff > expireThreshold) {
//                rspData.setCode(100);
//                rspData.setMsg("时间戳参数已过期!");
//                return rspData;
//            }
//        }
        // appid 校验
        if (StringUtils.isEmpty(appid)) {
            rspData.setCode(100);
            rspData.setMsg("appid参数不可为空!");
            return rspData;
        } else {
            if (!StringUtils.equals(appId, appid)) {
                rspData.setCode(100);
                rspData.setMsg("appid在系统中不存在，请联系管理员!");
                return rspData;
            } else {
//                String signature = request.getHeader("signature");
//                log.info("--------------Signature" + signature);
//                String newSignature = ApiSignatureUtils.createSign(requestBody, appid, nonce, timestamp, appSecret);
//                log.info("--------------newSignature" + newSignature);
//                if (!StringUtils.equals(newSignature, signature)) {
//                    rspData.setCode(100);
//                    rspData.setMsg("签名验证错误!");
//                    return rspData;
//                }
            }
        }

        return rspData;
    }
}
